package com.example.thread;

import java.util.concurrent.CountDownLatch;

/**
 * countdownlatch 是一个同步类工具，不涉及锁定，当count的值为零时当前线程继续运行，
 * 不涉及同步，只涉及线程通信的时候，使用它较为合适
 * 如果有资源争夺 还是需要加锁
 */
public class PrintAB2CDL {
    private static final int MAX_PRINT_NUM = 100;
    private static volatile int count = 0;

    public static void printAB() {
        // 声明CountDownLatch
        CountDownLatch countDownLatch = new CountDownLatch(2);

        new Thread(() -> {
            while (count < MAX_PRINT_NUM) {
                if (count % 2 == 0) {
                    System.out.println("num偶数:" + count);
                    count++;
                }
            }
            // 偶数线程执行完则计数器减一
            countDownLatch.countDown();
        }).start();

        new Thread(() -> {
            while (count < MAX_PRINT_NUM) {
                if (count % 2 == 1) {
                    System.out.println("num奇数:" + count);
                    count++;
                }
            }
            // 奇数线程执行完则计数器减一
            countDownLatch.countDown();
        }).start();

        try {
             countDownLatch.await();
        } catch (Exception e) {
        }
    }

    public static void main(String[] args) {
        printAB();
        System.out.println("main方法结束");
    }
}
